<template>
  <a-card
    :tab-list="tabKeys"
    :active-tab-key="activeTabKey"
    @tab-change="(key) => onTabChange(key)"
  >
    <div>
      <a-spin :spinning="loading">
        <a-row :gutter="16">
          <a-col :span="18">
            <div class="img-player-container">
              <div style="width: 320px">
                <a-button
                  type="primary"
                  :icon="h(StepBackwardOutlined)"
                  @click="moveToFirstImage"
                />
                <a-button type="primary" :icon="h(LeftOutlined)" @click="previousImage" />
                <a-button
                  type="primary"
                  :icon="h(CaretRightOutlined)"
                  @click="imageStartPlay"
                  v-if="!playStatus"
                />
                <a-button
                  type="primary"
                  :icon="h(StopOutlined)"
                  @click="imageStopPlay"
                  v-if="playStatus"
                />
                <a-button type="primary" :icon="h(RightOutlined)" @click="nextImage" />
                <a-button type="primary" :icon="h(StepForwardOutlined)" @click="moveToEndImage" />
              </div>
              <div style="width: 100%">
                <a-slider
                  v-model:value="aSliderValue"
                  :min="1"
                  :max="productCount"
                  :tip-formatter="aSliderFormatter"
                  @change="aSliderChange"
                />
              </div>
            </div>
            <div style="margin-top: 40px; text-align: center">
              <a-image
                :src="imageSrc"
                :preview="false"
                @click="showImagePreview"
                style="cursor: pointer"
                :fallback="getNoneImg()"
              />
            </div>
          </a-col>
          <a-col :span="6" class="time-col" style="padding-left: 0px; padding-right: 0px">
            <div style="margin-top: 10px; width: 100%">
              <div class="time-col-hour-title"> 日期 </div>
              <div>
                <a-date-picker
                  v-model:value="datePickerValue"
                  @change="dataPickerChange"
                  style="width: 70%; margin-left: 10px; margin-top: 10px"
                />

                <a-select
                  v-model:value="hourSelectValue"
                  :options="hourSelectValueList"
                  style="margin-left: 10px; width: 70px"
                  v-if="currentProduct?.dataTimeSelectType === DataTimeSelectEnum.HOURS"
                  @change="hourSelectChange"
                />
              </div>
            </div>
            <div style="margin-top: 20px">
              <div class="time-col-hour-title"> 时间 </div>
              <div
                class="time-col-hour-radio-group"
                v-if="currentProduct?.dataTimeListType === DataTimeListEnum.HOUR_LIST"
              >
                <a-radio-group
                  v-model:value="preHourRatioValue"
                  style="width: 100%"
                  button-style="solid"
                  @change="preHourRatioChange"
                >
                  <a-row :gutter="16">
                    <a-col
                      :span="6"
                      v-for="item in imageIndexList"
                      :key="item"
                      style="margin-bottom: 10px"
                    >
                      <a-radio-button :value="item.id">{{ item.ageing }}</a-radio-button>
                    </a-col>
                  </a-row>
                </a-radio-group>
              </div>
              <div
                class="time-col-hour-radio-group"
                v-if="currentProduct?.dataTimeListType === DataTimeListEnum.DATA_TIME_LIST"
              >
                <a-radio-group
                  v-model:value="preHourListValue"
                  style="width: 100%"
                  button-style="solid"
                  @change="preHourListChange"
                >
                  <a-row :gutter="16">
                    <a-col
                      :span="24"
                      v-for="item in imageIndexList"
                      :key="item"
                      style="margin-bottom: 10px"
                    >
                      <a-radio-button :value="item.id" style="width: 95%">{{
                        item.productTime
                      }}</a-radio-button>
                    </a-col>
                  </a-row>
                </a-radio-group>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-spin>
    </div>
  </a-card>
  <ImagePreview
    ref="imagePreviewModal"
    :imageIndex="imageIndex"
    :imageSrc="imageSrc"
    :productCount="productCount"
    :currentProduct="currentProduct"
    :imageIndexList="imageIndexList"
  />
</template>
<script setup lang="ts">
  import { ref, watch, onMounted, h, onDeactivated } from 'vue';
  import { useRouter } from 'vue-router';
  import {
    StepBackwardOutlined,
    LeftOutlined,
    CaretRightOutlined,
    StopOutlined,
    RightOutlined,
    StepForwardOutlined,
  } from '@ant-design/icons-vue';
  import { getProductList12, getProductByItemKey } from '../data';
  import { DataTimeSelectEnum, DataTimeListEnum } from '/@/enums/productEnum';
  import { ProductCategory3Type, ImageIndexType, ProductCategory1Enum } from '/@/util/product-type';
  import { fillFlagByItemKey } from '/@/util/product-image';
  import ImagePreview from './image-preview/index.vue';

  import Api from '/@/api/api-interface/image-search';

  import type { Dayjs } from 'dayjs';
  import dayjs from 'dayjs';

  import { HttpConfig } from '/@/api/http-config';

  const router = useRouter();

  interface TabKeyType {
    key: string | null;
    tab: string | null;
  }

  const tabKeys = ref<TabKeyType[]>();
  const activeTabKey = ref('');
  const currentProduct = ref<ProductCategory3Type>();
  const productCount = ref<number>(0); // 产品总数
  const aSliderValue = ref<number>(1);

  const hourSelectValue = ref(''); // 时次 select值
  const hourSelectValueList = ref<string[]>([]); // 时次 select值 列表

  const preHourRatioValue = ref<number>(); // 预报时次选中
  const preHourListValue = ref<number>();

  const imageIndex = ref<number>(1);
  const imageSrc = ref('');

  const imagePreviewModal = ref();

  const playStatus = ref(false);

  const imagePalyerTzimer = ref(0);

  const imageIndexList = ref<ImageIndexType[]>([]);

  const datePickerValue = ref<Dayjs>();

  const loading = ref(false);

  function reset() {
    productCount.value = 0;
    aSliderValue.value = 1;
    hourSelectValue.value = '';
    hourSelectValueList.value = [];
    preHourRatioValue.value = 0;
    preHourListValue.value = 0;
    imageIndex.value = 1;
    imageSrc.value = '';
    playStatus.value = false;
    imageIndexList.value = [];
    datePickerValue.value = dayjs();
    loading.value = false;
  }

  function getNoneImg() {
    return new URL(`../../../../assets/images/image_notexist.png`, import.meta.url).href;
  }

  function showImagePreview() {
    if (currentProduct.value) {
      imagePreviewModal.value.showModal();
    }
  }

  function moveToFirstImage() {
    imageIndex.value = 1;
    aSliderChange(imageIndex.value);
    aSliderValue.value = imageIndex.value;
    getImageUrl();
  }

  function previousImage() {
    if (imageIndex.value <= 1) {
      imageIndex.value = productCount.value;
    } else {
      imageIndex.value--;
    }
    aSliderChange(imageIndex.value);
    aSliderValue.value = imageIndex.value;
    getImageUrl();
  }

  function imageStartPlay() {
    playStatus.value = true;
    imagePalyerTzimer.value = window.setInterval(function startPlayerImage() {
      nextImage();
    }, 1000);
  }

  function imageStopPlay() {
    playStatus.value = false;
    window.clearInterval(imagePalyerTzimer.value);
  }

  function nextImage() {
    if (imageIndex.value >= productCount.value) {
      imageIndex.value = 1;
    } else {
      imageIndex.value++;
    }
    aSliderChange(imageIndex.value);
    aSliderValue.value = imageIndex.value;
    getImageUrl();
  }

  function moveToEndImage() {
    imageIndex.value = productCount.value;
    aSliderChange(imageIndex.value);
    aSliderValue.value = imageIndex.value;
    getImageUrl();
  }

  // tab change
  const onTabChange = (value: string) => {
    activeTabKey.value = value;
    initCurrentProduct(value);
    initImageIndexInfo();
  };

  // 滑动块 tilte 格式化
  const aSliderFormatter = (value: number) => {
    const list = imageIndexList.value;
    if (value && list.length > 0 && currentProduct.value) {
      const dataTimeSelectType = currentProduct.value.dataTimeSelectType;
      const dataTimeListType = currentProduct.value.dataTimeListType;
      if (dataTimeSelectType === DataTimeSelectEnum.HOURS) {
        if (dataTimeListType === DataTimeListEnum.HOUR_LIST) {
          return list[value - 1].ageing;
        }
        if (dataTimeListType === DataTimeListEnum.DATA_TIME_LIST) {
          return list[value - 1].productTime;
        }
      }

      if (dataTimeSelectType === DataTimeSelectEnum.NONE) {
        return list[value - 1].productTime;
      }
    }
    return value;
  };

  // 滑动块change
  function aSliderChange(value: number) {
    if (value && currentProduct.value) {
      const dataTimeListType = currentProduct.value.dataTimeListType;
      const imageIndexId = imageIndexList.value[value - 1].id;
      if (dataTimeListType === DataTimeListEnum.DATA_TIME_LIST) {
        preHourListValue.value = imageIndexId || 0;
      }
      if (dataTimeListType === DataTimeListEnum.HOUR_LIST) {
        preHourRatioValue.value = imageIndexId || 0;
      }
      imageIndex.value = value;
      getImageUrl();
    }
  }

  // 预报时次 radio change
  function preHourRatioChange(e) {
    if (imageIndexList.value) {
      let index = 0;
      for (const i in imageIndexList.value) {
        if (imageIndexList.value[i].id === e.target.value) {
          index = parseInt(i);
          break;
        }
      }
      aSliderValue.value = index + 1;
      imageIndex.value = index + 1;
      getImageUrl();
    }
  }

  // 预报时次 list change
  function preHourListChange(e) {
    if (imageIndexList.value) {
      let index = 0;
      for (const i in imageIndexList.value) {
        if (imageIndexList.value[i].id === e.target.value) {
          index = parseInt(i);
          break;
        }
      }

      aSliderValue.value = index + 1;
      imageIndex.value = index + 1;
      getImageUrl();
    }
  }

  // 获取tab key 列表
  function getTabKeyList(category1: string, category2: string) {
    const tabList: TabKeyType[] = [];
    const productList: ProductCategory3Type[] = getProductList12(category1, category2, 0);
    for (const i in productList) {
      tabList.push({ key: productList[i].itemKey, tab: productList[i].title });
    }
    tabKeys.value = tabList;
  }

  // 初始化当前产品信息
  function initCurrentProduct(itemKey: string) {
    currentProduct.value = getProductByItemKey(itemKey);
  }

  async function dataPickerChange(v) {
    datePickerValue.value = v;
    const hour = await getHourList();
    getImageList(hour);
  }

  function hourSelectChange(v) {
    getImageList(v);
  }

  async function getImageList(hour: string) {
    if (currentProduct.value) {
      loading.value = true;
      const newestImageParams = fillFlagByItemKey(currentProduct.value.itemKey || '');
      const imageListParams = {
        id: null,
        flag1: newestImageParams.flag1,
        flag2: newestImageParams.flag2,
        flag3: newestImageParams.flag3,
        productStartTime: dayjs(datePickerValue.value).format('YYYY-MM-DD 00:00:00'),
        productEndTime: dayjs(datePickerValue.value).format('YYYY-MM-DD 23:59:59'),
        hour: hour,
      };
      const imageListResult = await Api.imageList(imageListParams);
      const imgList = imageListResult.result;
      if (imageListResult.code === 0 && imgList.length > 0) {
        imageIndexList.value = imgList;
        productCount.value = imgList.length;

        preHourRatioValue.value = imgList[0].id;
        preHourListValue.value = imgList[0].id;
        imageIndex.value = 1;
        getImageUrl();
      } else {
        imageIndexList.value = [];
        productCount.value = 0;
        preHourRatioValue.value = 0;
        preHourListValue.value = 0;
        imageIndex.value = 1;
        imageSrc.value = getNoneImg();
      }
      loading.value = false;
    }
  }

  async function getHourList() {
    if (currentProduct.value) {
      const newestImageParams = fillFlagByItemKey(currentProduct.value.itemKey || '');
      let hour = '';
      if (currentProduct.value.dataTimeSelectType === DataTimeSelectEnum.HOURS) {
        loading.value = true;
        const hourListParams = {
          id: null,
          flag1: newestImageParams.flag1,
          flag2: newestImageParams.flag2,
          flag3: newestImageParams.flag3,
          productStartTime: dayjs(datePickerValue.value).format('YYYY-MM-DD 00:00:00'),
          productEndTime: dayjs(datePickerValue.value).format('YYYY-MM-DD 23:59:59'),
        };
        const hourListResult = await Api.hourList(hourListParams);
        if (hourListResult.code == 0 && hourListResult.result.length > 0) {
          const list: any = [];
          for (const i in hourListResult.result) {
            const h = {
              value: hourListResult.result[i],
            };
            list.push(h);
          }
          const newestHour = list[list.length - 1].value;
          hourSelectValueList.value = list;
          hourSelectValue.value = newestHour;
          hour = newestHour;
        } else {
          hourSelectValueList.value = [];
          hourSelectValue.value = '';
        }
        loading.value = false;
      }
      return hour;
    }
    return '';
  }

  // 初始化图片索引信息
  async function initImageIndexInfo() {
    loading.value = true;
    if (currentProduct.value) {
      reset();
      const newestImageParams = fillFlagByItemKey(currentProduct.value.itemKey || '');
      const newestImageResult = await Api.newestImage(newestImageParams);
      if (newestImageResult.code === 0 && newestImageResult.result.productTime != '') {
        datePickerValue.value = dayjs(newestImageResult.result.productTime);

        const hour = await getHourList();
        getImageList(hour);
        getImageUrl();
      } else {
        reset();
      }
    }
    loading.value = false;
  }

  function getImageUrl() {
    if (imageIndex.value && imageIndexList.value.length > 0) {
      const url = `${HttpConfig.HttpPrefix}/picImageServer/image/searchById/${
        imageIndexList.value[imageIndex.value - 1].id
      }`;
      imageSrc.value = url;
    } else {
      imageSrc.value = getNoneImg();
    }
  }

  // 在 onMounted 之前执行
  watch(
    () => router.currentRoute.value,
    (curRoute) => {
      const category1: string = curRoute.query.category1 as string;
      if (category1 === ProductCategory1Enum.FORCAST) {
        const category2: string = curRoute.query.category2 as string;
        const itemKey: string = curRoute.query.itemKey as string;
        activeTabKey.value = itemKey;
        getTabKeyList(category1, category2);
        initCurrentProduct(itemKey);
        initImageIndexInfo();
      }
    },
    { immediate: true },
  );

  onMounted(() => {
    initImageIndexInfo();
  });

  onDeactivated(() => {
    window.clearInterval(imagePalyerTzimer.value);
  });
</script>
<style lang="less" scoped>
  .img-player-container {
    background-color: #f1f4fb;
    display: flex;
    width: 100%;
    height: 35px;
  }

  .ant-slider {
    margin: 12px 30px;
  }

  .time-col {
    border: 1px solid #ddd;
    padding-left: 0px;
    padding-right: 0px;
  }

  .time-col-hour-title {
    height: 40px;
    margin-top: 10px;
    font-size: 17px;
    font-family: Microsoft YaHei;
    font-weight: bold;
    color: #0188e8;
    border-bottom: solid 4px #0188e8;
    padding-left: 20px;
  }
  .time-col-hour-radio-group {
    margin-top: 10px;
    text-align: center;
  }
</style>
